package com.atsmart.app.receiver;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import com.atsmart.app.BizApp;
import com.atsmart.app.R;
import com.atsmart.app.model.CheckDurationInfo;
import com.atsmart.app.model.CommonBody;
import com.atsmart.app.model.PositionInfo;
import com.atsmart.app.model.PositionShutDownInfo;
import com.atsmart.app.model.PositonsInfo;
import com.atsmart.app.sql.ShutDownSqlHelper;
import com.atsmart.app.utils.LocationUtils;
import com.atsmart.app.utils.PrefsUtils;
import com.atsmart.app.utils.StringUtil;
import com.atsmart.app.webservice.ServiceHelper;
import com.atsmart.app.webservice.ServiceHost;
import com.google.json.Gson;

/**
 * @ClassName: SendReceiver
 * @Description:
 * @author zhao
 * @date 2012-5-12 上午11:13:01
 */
public class SendReceiver extends BroadcastReceiver {
	public long stime = 0;

	@Override
	public void onReceive(final Context context, Intent intent) {
//		Log.e("SendReceiver", "sendReceiver is start");
		final String date = StringUtil.millToDate(BizApp.getInstance()
				.getSendtime());
		try {
			new Thread() {
				public void run() {
					boolean ff = System.currentTimeMillis() > (BizApp
							.getInstance().getLocTime() + 70000);
//					UserLog.getInstance().write("SendReceiver ff : = " + ff + StringUtil.getCurrentTime() + " , SendReceiver lat: = " + BizApp.getInstance().getLat() +" , lon: = "+ BizApp.getInstance().getLon() + StringUtil.getCurrentTime());
					if (BizApp.getInstance().isNetworkAvailable()
							|| BizApp.getInstance().isWiFiActive()) {
						if (BizApp.getInstance().getCurrentLocation() == null
								|| BizApp.getInstance().getLat() < 0.0001
								|| BizApp.getInstance().getLon() < 0.0001 || ff) {
					
							BizApp.getInstance().getmLocationClient().start();
							try {
								sleep(7000);
								int i = 0;
								while (!BizApp.getInstance().isLocation
										&& i < 11) {
									sleep(4000);
									i++;
								}

								if (BizApp.getInstance().isLocation) {
									ff = false;
									BizApp.getInstance().isLocation = false;
								}

								BizApp.getInstance().getmLocationClient()
										.stop();
							} catch (InterruptedException e) {
								e.printStackTrace();
//								UserLog.getInstance().writeException(e);
							}

						}
					}
					if (StringUtil.isEmptyOrNull(PrefsUtils.getResult())) {
						sendloc(ff, date);
					}
				}
			}.start();
		} catch (Exception e) {
			e.printStackTrace();
//			UserLog.getInstance().writeException(e);
		}
	}

	public void sendloc(boolean ff, String date) {
//		Log.e("SendReceiver", "sendloc");
//		UserLog.getInstance().write("sendLoc : = " + StringUtil.getCurrentTime());
		try {
			PositionInfo position = new PositionInfo();

			Gson gson = new Gson();
			CommonBody body = new CommonBody();
			body.setCommand(2);
			body.setImsi(BizApp.getInstance().getIMSI());
			body.setVersion(BizApp.getInstance()
					.getString(R.string.app_version));
			PositonsInfo positions = new PositonsInfo();
			positions.positions = new ArrayList<PositionInfo>();

			position.date = date;
			// Log.e("tag", String.valueOf(ff));
			// Log.e("tag", String.valueOf(position.date));
			Double lat_now = null;
			Double lon_now = null;
			if (BizApp.getInstance().isWiFiActive()
					|| BizApp.getInstance().isNetworkAvailable()) {
				lat_now = BizApp.getInstance().getLat();
				lon_now = BizApp.getInstance().getLon();
				position.lat = lat_now;
				position.lon = lon_now;
			} else {
				position.lat = 0.0;
				position.lon = 0.0;
			}
			position.address = "";

			// Log.e(" sendReceiver tag", "position.lat = " +lat_now);
			// Log.e(" sendReceiver tag", "position.lon = " +lon_now);
			// Log.e(" sendReceiver tag",
			// LocationUtils.getInstance().getLocationMsg());

			position.locationMsg = LocationUtils.getInstance().getLocationMsg();

			position.msgType = 2;// 巡检中

			if (BizApp.getInstance().start) {
				position.msgType = 1;// 巡检开始
			}
			if (BizApp.getInstance().end) {
				position.msgType = 3;// 巡检结束
			}
			BizApp.getInstance().start = false;
			BizApp.getInstance().end = false;
			position.type = 1;// 高精度gps

			positions.positions.add(position);

//			Log.e("巡检内容", gson.toJson(positions));
//			UserLog.getInstance().write("巡检内容: = " + gson.toJson(positions));

			ShutDownSqlHelper psql = new ShutDownSqlHelper();
			psql.open(BizApp.getInstance().getSqlHelper());
			// 无网络保存本地，待有网络时上传汇报,若返回定位地址不实时则退出。
			if ((!BizApp.getInstance().isNetworkAvailable() && !BizApp
					.getInstance().isWiFiActive())
					|| BizApp.getInstance().keeping == false) {
				PositionShutDownInfo pinfo = new PositionShutDownInfo();
//				UserLog.getInstance().write("无网络写入巡检sql: = " + gson.toJson(positions));
//				 Log.e("写入巡检sql", gson.toJson(positions));
				pinfo.setVer(gson.toJson(body));
				pinfo.setPos(gson.toJson(positions));
				pinfo.setType(3);// 巡检结束保存
				// for(int i=0; i<11; i++){
				psql.addAttribute(pinfo);
				// }

			} else {// 有网络检测sql中是否有保存内容，有--上传sql内容 无--巡检汇报

				PositionShutDownInfo pinfo = new PositionShutDownInfo();
				try {
					CheckDurationInfo info = ServiceHelper.getInstance()
							.postData(ServiceHost.reportLocationURL(),
									gson.toJson(body), gson.toJson(positions),
									CheckDurationInfo.class);

					if (info != null && info.getResult() == 0) {
//						Log.e("巡检成功","巡检成功： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
						// 上传成功
					} else {// 上传失败
//					 Log.e("上传失败写入巡检sql", gson.toJson(positions));
//						UserLog.getInstance().write("巡检失败： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
						pinfo.setVer(gson.toJson(body));
						pinfo.setPos(gson.toJson(positions));
						pinfo.setType(3);// 巡检结束保存
						// psql.addAttribute(pinfo);
						// for(int i=0; i<11; i++){
						psql.addAttribute(pinfo);
						// }
					}
				} catch (Exception e) {
//					Log.e("巡检异常", "巡检异常： = " + gson.toJson(positions) + " , 当前时间： = " + StringUtil.getCurrentTime() + "\r\t\n");
//					UserLog.getInstance().writeException(e);
					pinfo.setVer(gson.toJson(body));
					pinfo.setPos(gson.toJson(positions));
					pinfo.setType(3);// 巡检结束保存
					psql.addAttribute(pinfo);
					// for(int i=0; i<11; i++){
					// psql.addAttribute(pinfo);
					// }
					e.printStackTrace();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
//			UserLog.getInstance().writeException(e);
		}
	}

	public void saveToSDCard(String filename, String content) throws Exception {
		File file = new File(Environment.getExternalStorageDirectory(),
				filename);
		FileOutputStream outStream = new FileOutputStream(file, true);
		outStream.write(content.getBytes());
		outStream.close();
	}
}